import { delDeviceAlarmConfig, getDeviceAlarmConfigList } from "@/api/modules/iot/alarm";
import { getProfile } from "@/api/modules/model/profile";
import DialogBox from "@/components/DialogBox";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import AlarmLevel from "@/components/Sansan/Model/components/AlarmLevel";
import DataChart from "@/components/Sansan/Model/components/DataChart";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import { MessageType } from "@/enums/messageEnum";
import { alarmParam, SchemaNodeKey } from "@/utils/constants";
import { dataFormat, duration } from "@/utils/format";
import { showMsg, confirm, showTips } from "@/utils/util";
import ConfigDetail from "@/views/iot/alarm/components/configDetail";
import { Search, Refresh } from "@element-plus/icons-vue";
import moment from "moment";
import HistAlarmList from "./components/histAlarmList";
import "./alarm.scss";
import { gotoPage } from "@/utils/routerUtil";
import { RouterPath } from "@/enums/routerPath";
export default defineComponent({
	setup() {
		const dicts = reactive({
			...alarmParam
		});
		const profile = ref();
		provide(SchemaNodeKey.profile, profile);
		const initParam = reactive<any>({});
		const searchParam = reactive<any>({
			collapsed: true
		});
		const proTable = ref<any>();
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "alarmType", label: "告警类型" },
			{ prop: "devSn", label: "设备", search: { el: "input" } },
			{ prop: "key", label: "变量", search: { el: "input" } },
			{ prop: "rule", label: "报警配置" },
			{ prop: "updateTime", label: "更新时间" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];
		const buttonsList = ref<any>([
			// { title: "添加", icon: "iconbx-wrench", type: "primary" },
			// { title: "删除", icon: "icondownload" }
		]);
		const dataCallback = (data: any) => {
			let res = Array.isArray(data)
				? { datalist: data }
				: {
						datalist: data.records,
						total: data.total || 0,
						pageIndex: data.current,
						pageSize: data.size
				  };
			res.datalist = res.datalist.map((item: any) => {
				item.id = `${item.devProductId}-${item.devSn}-${item.key}`;
				return item;
			});
			return res;
		};
		const getTableList = async (params: any) => {
			return getDeviceAlarmConfigList({ ...params, ...searchParam });
			// return { result: { records: [{}] } };
		};
		const handerBtn = async (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "history":
					if (selected.length != 1) {
						showMsg("请选择一条记录记录", MessageType.warning);
						return;
					}
					const { result } = await getProfile({ idSn: selected[0].devSn });
					profile.value = result;
					dataChartDialog.detail = { ...selected[0] };
					dataChartDialog.title = `历史数据趋势-${selected[0].devSn}`;
					dataChartDialog.visible = true;
					break;
				case "conf":
					if (selected.length != 1) {
						showMsg("请选择要操作的记录", MessageType.warning);
						return;
					}
					configAlarmDialog.detail = { ...selected[0] };
					configAlarmDialog.title = `告警配置-${selected[0].devSn}`;
					configAlarmDialog.visible = true;
					break;
				case "detail":
					if (selected.length != 1) {
						showMsg("请选择要操作的记录", MessageType.warning);
						return;
					}
					alarmHistoryDialog.detail = { ...selected[0] };
					alarmHistoryDialog.title = `历史告警记录-${selected[0].devSn}`;
					alarmHistoryDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg("请选择要删除的配置项", MessageType.warning);
						return;
					}
					delConfig(selected);
					break;
			}
		};
		const delConfig = (dataList: any) => {
			confirm({ content: "确定删除当前选择的告警配置" }).then(async flag => {
				if (!flag) return;
				let { code } = await delDeviceAlarmConfig({ sn: dataList[0].devSn, key: dataList[0].key });
				let ok = showTips(code, "删除告警配置");
				ok && proTable.value.getTableList();
			});
		};

		//告警配置
		const configAlarmDialog = reactive({
			visible: false,
			detail: { key: "", devSn: "" },
			title: "告警配置"
		});
		//历史数据
		const dataChartDialog = reactive<any>({
			title: `历史数据趋势`,
			detail: { key: "", devSn: "" },
			visible: false
		});
		//历史告警
		const alarmHistoryDialog = reactive<any>({
			title: `历史告警`,
			detail: { key: "", devSn: "" },
			visible: false
		});
		return () => {
			return (
				<div class="real-alarm-page ">
					{/*变量数据趋势*/}
					<DialogBox
						class="dialog-dense"
						hideFooter
						v-model:visible={dataChartDialog.visible}
						width="75vw"
						title={dataChartDialog.title}
					>
						{dataChartDialog.visible ? (
							<DataChart dataKey={dataChartDialog.detail.key} class="bg-gray-100" height="55vh" />
						) : null}
					</DialogBox>
					{/*告警设置*/}
					<DialogBox
						title={configAlarmDialog.title}
						v-model:visible={configAlarmDialog.visible}
						footerLabel={["关闭"]}
						width="65vw"
					>
						{configAlarmDialog.visible ? (
							<ConfigDetail sn={configAlarmDialog.detail.devSn} sensorKey={configAlarmDialog.detail.key} />
						) : null}
					</DialogBox>
					{/*历史告警*/}
					<DialogBox
						title={alarmHistoryDialog.title}
						v-model:visible={alarmHistoryDialog.visible}
						footerLabel={["关闭"]}
						width="65vw"
					>
						{alarmHistoryDialog.visible ? (
							<HistAlarmList fiexdTarget sn={alarmHistoryDialog.detail.devSn} sensorKey={alarmHistoryDialog.detail.key} />
						) : null}
					</DialogBox>
					<BaseSearchForm v-model:collapsed={searchParam.collapsed}>
						<el-form class="flex pt-4 pl-4 pr-4 bg-white" style="">
							<el-form-item class="search-item" label="告警类型">
								<el-input v-model={searchParam.alarmType} placeholder="告警类型" />
							</el-form-item>
							<el-form-item class="search-item" label="告警条件">
								<el-select v-model={searchParam.limitType} style="width:150px" clearable>
									{Object.values(alarmParam.warningMode).map(level => {
										return <el-option label={level.label} value={level.value}></el-option>;
									})}
								</el-select>
							</el-form-item>
							<el-form-item class="search-item" label="告警设备">
								<el-input v-model={searchParam.sn} placeholder="告警设备" style="width:150px" />
							</el-form-item>
							<el-form-item class="search-item" label="告警变量">
								<el-input v-model={searchParam.keyName} placeholder="告警变量" style="width:150px" />
							</el-form-item>

							{/* 高级查询 */}
							{searchParam.collapsed ? null : (
								<el-form-item class="search-item" label="告警等级">
									<el-select v-model={searchParam.alarmLevel} clearable>
										{Object.values(alarmParam.warningLevel).map(level => {
											return <el-option label={level.label} value={level.value}></el-option>;
										})}
									</el-select>
								</el-form-item>
							)}
							<el-form-item class="search-item">
								<el-button type="primary" icon={Search} onClick={() => proTable.value.getTableList()}>
									搜索
								</el-button>
								<el-button
									icon={Refresh}
									onClick={() => {
										for (let key in searchParam) {
											searchParam[key] = null;
										}
										proTable.value.getTableList();
									}}
								>
									重置
								</el-button>
							</el-form-item>
						</el-form>
					</BaseSearchForm>
					<div class="mt-4 ignore-search-split">
						<ProTable
							ref={proTable}
							toolbar={["grid"]}
							viewType="grid"
							custSearch
							title={buttonsList.value.length ? "" : "告警配置"}
							onSearchCollapsed={val => (searchParam.collapsed = val)}
							columns={columns}
							initParam={initParam}
							gridSpan={6}
							requestApi={getTableList}
							dataCallback={dataCallback}
						>
							{{
								tableHeader: (scope: any) => {
									return buttonsList.value?.map((item: any) => {
										return (
											<el-button class={`iconfont ${item.icon}`} onClick={() => handerBtn(item.path, scope)} type={item.type}>
												{item.title}
											</el-button>
										);
									});
								},
								cardBody: (scope: any) => {
									return (
										<div class="config-card shadow-md">
											<div class="bg"></div>
											<div class="container">
												<div class="title">
													<el-link
														title="加载设备详情"
														type="primary"
														onClick={() => gotoPage(RouterPath.deviceDetail, { sn: scope.row.devSn })}
													>
														<div class="master-title">{scope.row.devSn}</div>
													</el-link>
													<div class="sub-title" title="查看历史数据">
														<el-link type="primary" onClick={() => handerBtn("history", scope.row)}>
															{scope.row.key}
														</el-link>
													</div>
												</div>
												<div class="body">
													{scope.row.warning?.map((conf: any) => {
														let item = Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode);
														return (
															<div class="alarm-group">
																<div class="type-label">{conf.alarmType}</div>
																<div class="param-info">
																	<div class="param-label">{item?.label} </div>
																	<div class="param-value">
																		{/* 上限 */}
																		{conf.warningMode == alarmParam.warningMode.max.value ? (
																			<div>{conf.warningUlimit || 0}</div>
																		) : null}

																		{/* 下限 */}
																		{conf.warningMode == alarmParam.warningMode.min.value ? (
																			<div>{conf.warningDlimit || 0}</div>
																		) : null}

																		{/* 上下限 */}
																		{conf.warningMode == alarmParam.warningMode.range.value ? (
																			<div>
																				{conf.warningDlimit || 0} ~ {conf.warningUlimit || 0}
																			</div>
																		) : null}

																		{/* 下限 */}
																		{conf.warningMode == alarmParam.warningMode.eq.value ? (
																			<div>{conf.warningElimit || 0}</div>
																		) : null}
																	</div>
																</div>
															</div>
														);
													})}
												</div>
												<div class="footer flex justify-between pr-2">
													<el-button
														class="iconfont icontrash-2"
														link
														title="删除告警配置"
														type="danger"
														onClick={() => handerBtn("del", scope.row)}
													>
														删除配置
													</el-button>
													<el-button
														class="iconfont iconbx-list-ol"
														link
														title="查看告警配置详情"
														type="primary"
														onClick={() => handerBtn("detail", scope.row)}
													>
														历史告警
													</el-button>
													<el-button
														class="iconfont iconsettings"
														link
														title="查看告警配置详情"
														type="primary"
														onClick={() => handerBtn("conf", scope.row)}
													>
														告警配置
													</el-button>
												</div>
											</div>
										</div>
									);
								},

								alarmType: (scope: any) => {
									return (
										<span type="primary">
											{!scope.row.warning || !scope.row.warning.length ? "--" : null}
											{scope.row.warning
												?.map((item: any) => {
													return item.alarmType;
												})
												.join(",")}
										</span>
									);
								},
								duration: (scope: any) => {
									return duration(moment(scope.row.createTime));
								},
								rule: (scope: any) => {
									return (
										<el-popover show-after={500}>
											{{
												reference() {
													return (
														<el-link type="primary" onClick={() => handerBtn("conf", scope.row)}>
															{!scope.row.warning || !scope.row.warning.length ? "--" : null}
															{scope.row.warning
																?.map((conf: any) => {
																	return Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode)
																		?.label;
																})
																.join(",")}
														</el-link>
													);
												},
												default() {
													return (
														<div class="leading-6">
															{!scope.row.warning || !scope.row.warning.length ? "无告警配置" : null}
															{scope.row.warning?.map((conf: any) => {
																let item = Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode);
																return (
																	<>
																		<div class="flex pb-4">
																			<div class="w-20 text-right">{item?.label}：</div>
																			{/* 上限 */}
																			{conf.warningMode == alarmParam.warningMode.max.value ? (
																				<div>{conf.warningUlimit}</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.min.value ? (
																				<div>{conf.warningDlimit}</div>
																			) : null}

																			{/* 上下限 */}
																			{conf.warningMode == alarmParam.warningMode.range.value ? (
																				<div>
																					{conf.warningDlimit} ~ {conf.warningUlimit}{" "}
																				</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.eq.value ? (
																				<div>{conf.warningElimit}</div>
																			) : null}
																		</div>
																	</>
																);
															})}
														</div>
													);
												}
											}}
										</el-popover>
									);
								},
								key: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => handerBtn("history", scope.row)}>
											{scope.row.key}
										</el-link>
									);
								},
								devSn: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => gotoPage(RouterPath.deviceDetail, { sn: scope.row.devSn })}>
											<div class="master-title">{scope.row.devSn}</div>
										</el-link>
									);
								},
								warningMode: (scope: any) => {
									return Object.values(dicts.warningMode).find(item => item.value == scope.row.warningMode)?.label;
								},
								level: (scope: any) => {
									return <AlarmLevel v-model={scope.row.level} />;
								},
								isError: (scope: any) => {
									return Object.values(dicts.isError).find(item => item.value == scope.row.isError)?.label;
								},
								autoDone: (scope: any) => {
									return Object.values(dicts.autoDone).find(item => item.value == scope.row.autoDone)?.label;
								},
								triggerType: (scope: any) => {
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								warningType: (scope: any) => {
									return Object.values(dicts.warningType).find(item => item.value == scope.row.warningType)?.label;
								},
								updateTime: (scope: any) => {
									return dataFormat("datetime", scope.row.updateTime);
								},
								operation: (scope: any) => {
									return (
										<>
											<el-link type="danger" onClick={() => handerBtn("del", scope.row)}>
												删除
											</el-link>
											<el-link type="primary" onClick={() => handerBtn("detail", scope.row)}>
												更多
											</el-link>
										</>
									);
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
